package com.example.permission.controller;

import cn.hutool.core.util.StrUtil;
import com.example.common.enetiy.AccessLog;
import com.example.common.utils.HttpAnalysisUtil;
import com.example.common.utils.RedisUtils;
import com.example.permission.model.req.LoginDTO;
import com.example.permission.model.req.RegisterDTO;
import com.example.permission.model.resp.CaptchaDTO;
import com.example.permission.model.resp.LoginVO;
import com.example.permission.service.AuthService;
import com.wf.captcha.ArithmeticCaptcha;
import jakarta.servlet.ServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author qwer3
 * @version 1.0.0
 * @create 2025/10/30 21:06
 */
@RestController
@RequestMapping("/api/sys/auth")
@RequiredArgsConstructor
public class LoginController {
    private final AuthService authService;
    private final RedisUtils redisUtils;

    @GetMapping("/captcha")
    public CaptchaDTO getCaptcha() {
        boolean flag = true;
        String base64 = "";
        String answer = "";
        while (flag) {
            ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48);
            captcha.setLen(2);
            captcha.setFont(new Font("Arial", Font.BOLD, 32));
            answer = captcha.text();
            long aLong = Long.parseLong(answer);
            if (aLong >= 0L) {
                base64 = captcha.toBase64();
                flag = false;
            }
        }

        String captchaKey = UUID.randomUUID().toString();
        redisUtils.set("sys:captcha:" + captchaKey, answer, 1, TimeUnit.HOURS);

        return CaptchaDTO.builder()
                .captchaKey(captchaKey)
                .captchaCode(base64)
                .build();
    }

    @PostMapping("/login")
    public LoginVO login(@RequestBody LoginDTO loginDTO, ServletRequest request) {
        if (StrUtil.isBlank(loginDTO.getCaptchaKey()) || StrUtil.isBlank(loginDTO.getCaptchaCode())) {
            throw new RuntimeException("验证码验证失败，请刷新重试Ciallo～(∠・ω< )⌒★");
        }
        String cacheKey = "sys:captcha:" + loginDTO.getCaptchaKey();
        if (!redisUtils.hasKey(cacheKey)) {
            throw new RuntimeException("验证码验证失效，请刷新重试Ciallo～(∠・ω< )⌒★★");
        }

        String answer = redisUtils.get(cacheKey);
        if (!Objects.equals(loginDTO.getCaptchaCode(), answer)) {
            throw new RuntimeException("验证码验证错误，请刷新重试Ciallo～(∠・ω< )⌒★★★");
        }
        AccessLog accessLog = HttpAnalysisUtil.buildAccessLog(request);
        String token = authService.login(loginDTO, accessLog);
        return LoginVO.builder().token(token).build();
    }

    @PostMapping("/register")
    public void register(@RequestBody RegisterDTO registerDTO) {
        authService.register(registerDTO);
    }

    @PostMapping("/logout")
    public void logout() {
        authService.logout();
    }

}
